package com.xyzh.application.common.util;

import cn.hutool.core.util.ObjectUtil;
import com.xyzh.application.base.vo.AuthorUser;
import com.xyzh.application.common.exceptionHandler.ServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

/**
 * @author: JZB
 * @date: 2022/11/10 13:51
 * @description: 安全服务工具类
 */
public class SecurityUtils {

    private SecurityUtils(){

    }

    /**
     * 用户ID
     **/
    public static String getUserId()
    {
        AuthorUser user=getAuthorUser();
        try
        {
            if(ObjectUtil.isNotEmpty(user)) {
                return getAuthorUser().getId();
            }else{
                return "";
            }
        }
        catch (Exception e)
        {
            throw new ServiceException("unauthorized",401);
        }
    }

    /**
     * 获取用户
     **/
    public static AuthorUser getAuthorUser()
    {
        try
        {
            return (AuthorUser) getAuthentication().getPrincipal();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }
    public static AuthorUser getLoginUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        try {

            if(   ((OAuth2Authentication) authentication).getUserAuthentication() !=null){
                return  (AuthorUser) ((OAuth2Authentication) authentication).getUserAuthentication().getPrincipal()  ;
            }else {
                return null;
            }

        }catch (Exception e){
            return null;
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication()
    {
        return SecurityContextHolder.getContext().getAuthentication();
    }
}
